package com.jingbit.ai.utils;

import android.content.Context;
import android.os.Build;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import android.util.ArrayMap;
import android.util.Log;
import android.widget.Toast;

import com.jingbit.ai.helper.StringHelper;

import java.util.HashMap;
import java.util.Locale;

public class TTSUtil {
    public static final String TAG = "jingbit:TTSUtil";

    private static TextToSpeech textToSpeech;
    private static ArrayMap<Long, String> mSpeaks;

    public static final String[] USER_NAMES = {"沙沙同学"};
    public static final String[] BREAK_CMDS = {"^停止说话", "^闭嘴", "^好了好了", "^好了，好了", "^打住", "^打住打住", "^打住，打住", "^好了我知道了", "^好了，我知道了", "^行了我知道了", "^行了，我知道了"};

    private static volatile long speaked_time = 0;

    public static boolean init(final Context ctx) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            mSpeaks = new ArrayMap<Long, String>();
        }
        textToSpeech = new TextToSpeech(ctx, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if (status == TextToSpeech.SUCCESS) {
                    int result = textToSpeech.setLanguage(Locale.CHINA);
                    if (result != TextToSpeech.LANG_COUNTRY_AVAILABLE
                            && result != TextToSpeech.LANG_AVAILABLE) {
                        Toast.makeText(ctx, "TTS暂时不支持这种语音的朗读！",
                                Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
        return true;
    }

    public static void doSpeak(String word) {
        doSpeak(word, false);
    }

    public static void doSpeak(String word, boolean add) {
        word = word.replace("\t", "");
        word = word.replace("\n", "");
        word = word.replace("\r", "");
        mSpeaks.put(System.currentTimeMillis(), word);
        HashMap<String, String> hashTts = new HashMap<String, String>();
        hashTts.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "id");
        textToSpeech.speak(word,
                add ? TextToSpeech.QUEUE_ADD : TextToSpeech.QUEUE_FLUSH, hashTts);
        textToSpeech.setSpeechRate(2f);
        textToSpeech.setOnUtteranceProgressListener(new UtteranceProgressListener() {
            @Override
            public void onStart(String utteranceId) {
                Log.d(TAG, "onStart：" + utteranceId);
                speaked_time = 0;
            }

            @Override
            public void onDone(String utteranceId) {
                Log.d(TAG, "onDone：" + utteranceId);
                speaked_time = System.currentTimeMillis();
            }

            @Override
            public void onError(String utteranceId) {
                Log.d(TAG, "onError：" + utteranceId);
            }
        });
    }

    /**
     * 闭嘴
     */
    public static void doShutup() {
        if (textToSpeech.isSpeaking()) {
            doSpeak("", false);
        }
    }

    /**
     * 是否说话中
     *
     * @return
     */
    public static boolean isSpeaking() {
        return textToSpeech.isSpeaking();
    }

    public static boolean isSpeaking(long nlp_time) {
        Log.d(TAG, "handleMessage startChat: " + nlp_time + "---" + speaked_time + "---" + (nlp_time - speaked_time));
        if (isSpeaking() || nlp_time - speaked_time <= 2000) {
            return true;
        }
        return false;
    }

    /**
     * 判斷是否在一定時間內說過的話
     *
     * @param duration
     * @param word
     * @return
     */
    public static boolean isSpeaked(int duration, String word) {
        return isSpeaked(duration, word, 0.9d);
    }

    public static boolean isSpeaked(int duration, String word, double max_rato) {
        if (word.equals("") || word == null) {
            return false;
        }
        for (long time : mSpeaks.keySet()) {
            String speaked = mSpeaks.get(time);
            double simple = StringHelper.similarityRatio(speaked, word);
            if (speaked.contains(word) || simple >= max_rato) {
                return true;
            }
        }
        return false;
    }

    public static String isUserName(String word, double max_rato) {
        return isValidCmd(USER_NAMES, word, max_rato);
    }

    public static String isBreakCmd(String word, double max_rato) {
        return isValidCmd(BREAK_CMDS, word, max_rato);
    }

    public static String isValidCmd(String[] cmds, String word, double max_rato) {
        if (word.equals("") || word == null) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < cmds.length; i++) {
            String cmd = cmds[i];
            if (word.length() < cmd.length()) {
                continue;
            }
            sb.setLength(0);
            for (char c : cmd.toCharArray()) {
                int index = word.indexOf(c + "");
                if (index != -1) {
                    sb.append(c);
                }
            }
            if (sb.length() == 0) {
                continue;
            }
            double ratio = sb.length() / (cmd.toCharArray().length * 1.0d);
            System.out.println(TAG + "：isValidCmd: " + sb.toString() + "--- " + ratio + " --- " + word + " --- " + cmd);
            if (ratio >= max_rato && word.contains(sb.toString())) {
                return cmd;
            }
        }
        return "";
    }

}
